/*
 * @Author: zxc
 * @Date: 2021-01-24 17:28:17
 * @LastEditTime: 2021-01-24 17:37:16
 * @LastEditors: zxc
 * @Description: monad函子
 */
const fs = require("fs")
const fp = require("lodash/fp") // IO Monad
class IO {
  static of(x) {
    return new IO(function () {
      return x
    })
  }
  constructor(fn) {
    this._value = fn
  }
  map(fn) {
    return new IO(fp.flowRight(fn, this._value))
  }
  join() {
    return this._value()
  }
  flatMap(fn) {
    return this.map(fn).join()
  }
}
let readFile = function (filename) {
  return new IO(function () {
    return fs.readFileSync(filename, "utf-8")
  })
}
let print = function (x) {
  return new IO(function () {
    console.log(x)
    return x
  })
}
let r = readFile("../../package.json").map(fp.toUpper).flatMap(print).join()
